<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'

require('./spider') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    optionTitleText: {
      type: String,
      default: ''
    },
    categories:{
      type: Array,
      default: []
    },
    nodes:{
      type: Array,
      default: []
    },
    edges:{
      type: Array,
      default: []
    },
    repulsion:{
      type: Number,
      default: 1000
    },
  },
  data() {
    return {
      chart: null,
      option:{
        title: {
          text: this.optionTitleText,
          padding: 10,
        },
        backgroundColor: '#fff',
        legend: [{
          orient: 'vertical',
          left: 'right',
          data: this.categories.map(function (a) {
            return a.name;
          })
        }],
        series: [
          {
            type: 'graph',
            layout: 'force',
            animation: true,
            label: {
              show: true,
              position: 'right',
              formatter: '{b}'
            },
            draggable: true,
            data: this.nodes,
            categories: this.categories,
            force: {
              edgeLength: 5,
              repulsion: this.repulsion,
              gravity: 0.2
            },
            edges: this.edges,
          }
        ]
      }
    }
  },
  watch:{
    optionSeries(newValue,oldValue){
      this.option.title.text=newValue
      this.chart.setOption(this.option);
    },
    nodes(newValue,oldValue){
      this.option.series[0].data=newValue
      this.chart.setOption(this.option);
    },
    edges(newValue,oldValue){
      this.option.series[0].edges=newValue
      this.chart.setOption(this.option);
    },
    categories(newValue,oldValue){
      this.option.series[0].categories=newValue
      this.option.legend[0].data=newValue.map(function (a) {
        return a.name;
      })
      this.chart.setOption(this.option);

    },
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'spider')
      this.chart.setOption(this.option)
    }
  }
}
</script>
